//
//  ITRemindManager.m
//  Water
//
//  Created by seven on 2020/8/9.
//  Copyright © 2020 seven. All rights reserved.
//

#import "ITRemindManager.h"

//#import "AppDelegate+Push.h"

#import <UserNotifications/UserNotifications.h>

#import <EventKit/EventKit.h>

#import <UIKit/UIKit.h>

#import "ITPushModel.h"
#import "ITErrorTipView.h"
#define LastAddPushDay @"LastAddPushDay"
@implementation ITRemindManager

+ (instancetype)shareManager{
    static ITRemindManager *__manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __manager = ITRemindManager.new;
    });
    return __manager;
}

 
/**
 *  将App事件添加到系统日历提醒事项，实现闹铃提醒的功能
 *
 *  @param title      事件标题
 *  @param location   事件位置
 *  @param startDate  开始时间
 *  @param endDate    结束时间
 *  @param allDay     是否全天
 *  @param alarmArray 闹钟集合
 */

- (void)createEventCalendarTitle:(NSString *)title
                        location:(NSString *)location
                       startDate:(NSDate *)startDate
                         endDate:(NSDate *)endDate
                          allDay:(BOOL)allDay
                      alarmArray:(NSArray *)alarmArray;{
    __weak typeof(self) weakSelf = self;
    
    EKEventStore *eventStore = [[EKEventStore alloc] init];
    
    if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
    {
        [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                __strong typeof(weakSelf) strongSelf = weakSelf;
                if (error)
                {
                    [ITErrorTipView showWithAction:nil];
                    
                }else if (!granted){
                    
                    [ITErrorTipView showWithTitle:nil des:LocalTitle(@"No Reminder Calendars Permission!") actionTitle:LocalTitle(@"Go") Action:^(id  _Nullable obj, CustomActionType idx) {
                        if (idx == cat_done) {
                            [self goToAppSystemSetting];
                        }
                    }];
                    
                }else{
                    
                    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
                    event.title     = title;
                    event.location = location;
                    
                    NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
                    [tempFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
                    
                    NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:@[[eventStore defaultCalendarForNewEvents]]];
                    NSArray *events = [eventStore eventsMatchingPredicate:predicate];
                    for (EKEvent *e in events) {
                        if ([e.title isEqualToString:title]) {
                            [eventStore removeEvent:e span:EKSpanThisEvent error:nil];
                        }
                    }
                    [eventStore commit:nil];
                    
                    
                    event.startDate = startDate;
                    event.endDate   = endDate;
                    event.allDay = allDay;
                    
                    //添加提醒
                    if (alarmArray && alarmArray.count > 0) {
                        
                        for (NSString *timeString in alarmArray) {
                            [event addAlarm:[EKAlarm alarmWithRelativeOffset:[timeString integerValue]]];
                        }
                    }
                    
                    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
                    NSError *err;
                    [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
                    
                    //[AppUtils showInfo:[AppUtils titleForKey:@"Success! Seize any %@making opportunity!", [ITGeneralManager.defaultManager getWordWithIdx:4]]];

                    [AppUtils trackMTAEventNo:@"vq_20006"];
                    
                }
            });
        }];
    }
}


- (void)addLocalNoticeWithDate:(NSDate *)date
                         title:(NSString *)title
                       content:(NSString *)content
                    identifier:(NSString *)identifier
                      userInfo:(NSDictionary *)userInfo
                        repeat:(BOOL)repeat{

    
    if (content.length == 0) {
        return;
    }
    
    if (!date) {
        date = [[NSDate date] dateByAddingSeconds:1];
    }
    {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        UNMutableNotificationContent *nContent = [[UNMutableNotificationContent alloc] init];
        // 标题
        nContent.title = title;
        // 内容
        nContent.body = content;
        // 声音
        if (AppUtils.DICT_WORK_MODE) {
            nContent.sound = [UNNotificationSound soundNamed:@"push_sound.mp3"];
        }else {
            nContent.sound = [UNNotificationSound defaultSound];
        }
        nContent.userInfo = userInfo;
        
        //如果想重复可以使用这个,按日期
        NSDateComponents *components = [[NSDateComponents alloc] init];
        //NSLog(@"weekday %ld, %ld, %ld", date.hour, date.minute, date.second);
        components.hour = (NSInteger)date.hour;
        components.minute = (NSInteger)date.minute;
        components.second = (NSInteger)date.second;
        
        UNCalendarNotificationTrigger *calendarTrigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:repeat];
    
        // 添加通知的标识符，可以用于移除，更新等操作  多个通知一定要设置不同的id否则覆盖
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:nContent trigger:calendarTrigger];
        
        [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
            NSLog(@"成功添加推送");
        }];
    }
}

- (void)removeLocalPush{

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

    NSArray *arr = @[@"local_daily_push_1", @"local_daily_push_2", @"local_daily_push_3"];
    // 移除 待处理的通知
    [center removePendingNotificationRequestsWithIdentifiers:arr];
    // 移除 已经处理的通知
    [center removeDeliveredNotificationsWithIdentifiers:arr];
    
    // 移除所有的通知
    //[center removeAllDeliveredNotifications];
    //[center removeAllPendingNotificationRequests];
    [NSUserDefaults saveValue:nil forKey:LastAddPushDay];
}

- (void)addLocalPush{
    WEAKSELF
    [self checkUserNotificationPermission:^(BOOL isOn) {
        if (isOn) {
            /*
            int addDay = [[NSUserDefaults getValueForKey:LastAddPushDay] intValue];
            int dayCount = [NSDate dayCount];
            if (addDay > 0) {
                return;
            }
            [NSUserDefaults saveValue:@(dayCount) forKey:LastAddPushDay];
            //*/
            
            [weak_self removeLocalPush];
            ITCommonConfig *t = [ITGeneralManager.defaultManager configDicWithKey:@"DICT_LOCAL_PUSH_DEF"];
            if (t == nil) {
                return;
            }
            NSString *tmp = t.field[@"array"];
            NSArray *arr = [tmp jsonValueDecoded];
            if (arr.count == 0) {
                return;
            }
            /*
            NSArray *arr = @[
                @{@"title":LocalTitle(@"Good morning"), @"des": LocalTitle(@"Breakfast is a good healthy habit"), @"id" : @"local_daily_push_1", @"time": @"08:00"},
                @{@"title":LocalTitle(@"Hi，My friend"), @"des": LocalTitle(@"Take a 10-minute nap and you'll have a high-energy afternoon"), @"id" : @"local_daily_push_2", @"time": @"13:00"},
                @{@"title":LocalTitle(@"Good Job"), @"des": LocalTitle(@"May you have a good dream after a busy day"), @"id" : @"local_daily_push_3", @"time": @"20:30"},
            ];//*/
            
            for (int i=0 ; i<arr.count; i++) {
                NSDictionary *tmp = arr[i];
                NSString *title = tmp[@"title"];
                NSString *des = tmp[@"content"];
                NSString *_id = [@"local_daily_push_" stringByAppendingFormat:@"%d",i+1];
                NSDate *d = [NSDate dateWithString:tmp[@"time"] format:@"HH:mm"];
                [weak_self addLocalNoticeWithDate:d title:title content:des identifier:_id userInfo:tmp repeat:YES];
            }
        }else {
            MainDelay(0.1, ^{
                [weak_self showAlertView];
            });
        }
    }];
}

#pragma mark - UserNotification

- (void)checkUserNotificationPermission:(void(^)(BOOL isOn))callback { // 判断用户是否允许接收通知
    __block BOOL isOn = NO;
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        if (settings.notificationCenterSetting == UNNotificationSettingEnabled) {
            isOn = YES;
            NSLog(@"打开了通知");
        }else {
            isOn = NO;
            NSLog(@"关闭了通知");
        }
        if (callback) {
            callback(isOn);
        }
    }];
}

- (void)checkUserNotificationEnable:(BOOL)showAlert callBack:(void(^)(BOOL isOn))callback;{
    WEAKSELF
    [self checkUserNotificationPermission:^(BOOL isOn) {
        if (!isOn) {
            if (showAlert) {
                MainDelay(0.1, ^{
                    [weak_self showAlertView];
                });
            }
        }
        if (callback) {
            callback(isOn);
        }
    }];
}

- (void)showAlertView {
    WEAKSELF
    [ITErrorTipView showWithTitle:nil des:[AppUtils titleForKey:@"Failed to get notification permission, please go ahead to set"] actionTitle:[AppUtils titleForKey:@"Setting"] Action:^(id  _Nullable obj, CustomActionType idx) {
        if (idx == cat_done) {
            [weak_self goToAppSystemSetting];
        }
    }];
}

// 如果用户关闭了接收通知功能，该方法可以跳转到APP设置页面进行修改
- (void)goToAppSystemSetting {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIApplication *application = [UIApplication sharedApplication];
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([application canOpenURL:url]) {
            if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                [application openURL:url options:@{} completionHandler:nil];
            }
        }
    });
}

@end
